
#include <stdlib.h>//
#include <stdio.h>//
#include <fcntl.h>
#include <ctype.h>//
#include <unistd.h>//
#include <signal.h>
#include <time.h>//
#include <pthread.h>//
#include <string.h>//
#include <errno.h>//
#include <getopt.h>//
#include <libgen.h>//
#include <stdlib.h>//
#include <sys/types.h>//
#include <sys/socket.h>//
#include <arpa/inet.h>//
#include <sys/epoll.h>//
#include <sys/resource.h>


#define BACKLOG 		13
#define		MAX_EVENTS	512
static		int    g_stop=0;


void print_usage(char *progname);

void sig_stop(int signum);

int connect_server(char *ip, int serv_port);




int main(int argc,char*argv[])
{
	int	listen_fd,client_fd;//参数
	int	serv_port=0;
	int	daemon_run=0;
	char	*progname=NULL;
	struct sockaddr_in      cli_addr;
	socklen_t               len = 20;
	int	opt;
	int	rv=-1;
	int	sock_fd;
        char    *ip;
	int	i,j;
	int	found;
	int	log_fd;
	char	buf[1024];
	int	epollfd;
	int	events;
	struct epoll_event	event;
	struct epoll_event	event_array[MAX_EVENTS];//同时处理多少个客户端



	struct option   opts[]={
	{"daemon",no_argument,NULL,'b'},
	{"ip",required_argument,NULL,'i'},
        {"port",required_argument,NULL,'p'},
	{"time",required_argument,NULL,'t'},
	{"help",no_argument,NULL,'h'},
	{NULL,0,NULL,0}
	};

	progname=basename(argv[0]);

	while((opt=getopt_long(argc,argv,"bi:p:t:h",opts,NULL))!=-1)
	{
		switch(opt)
		{
			case'd':
				daemon_run=1;
				break;
			case'i':
				//
				break;
			case'p':
				serv_port=atoi(optarg);

			case't':
				//
				break;
			case'h':
				print_usage(progname);
				return    EXIT_SUCCESS;

			default:		
				break;
		
		
		}

	}


        if(! ip || !serv_port)
	{
		print_usage(progname);
		return -1;
	}


	if(daemon_run)
	{
		printf("Program %s is running at the background now\n", argv[0]);
		log_fd=open("temper_server.log",O_CREAT | O_RDWR,0666);
		if(log_fd<0)
		{	
			printf("open the logfile failure:%s\n",strerror(errno));
			return -2;
		}
		
	}
        dup2(log_fd, STDOUT_FILENO);
        dup2(log_fd, STDERR_FILENO);

        if ((daemon(1, 1)) < 0)
        {
            printf("Deamon failure : %s\n", strerror(errno));
            return 0;
        }

/*
	openlog("daemon",LOG_CONS | LOG_PID,0);
	syslog(LOG_NOTICE,"program '%s' start running\n",progname);
	syslog(LOG_WARNING,"program '%s' running with a warning message\n",progname);
	syslog(LOG_EMERG,"program '%s' running with a emergency message\n",progname);
      
*/

	
}



void   print_usage(char *progname)
{
	printf("-b(daemon)running background\n");
	printf("-i(--ip):\n");
	printf("-p(--port):\n");
	printf("-t(--time):(eg.:2021-1-1)\n");
	printf("-h(help):heip information\n");
	printf("\n exampla:%s -b -i 127.0.0.1 -p 8888 -t 30s \n",progname);

	return;
}

//安装信号
/*signal(SIGUSR1,sig_stop);

void sig_stop(signum)
{
	if(SIGUSR1=signum)
	{
		g_stop=1;
	}
	return ;

}

*/

//日志


/*
if(flag)
{
	fd_log=open("temper_server.log",O_CREAT | O_RDWR,0666);
	if(fd_log<0)
	{
		printf("open the logfile failure:%s\n",strerror(errno));
		return -3;
	}
	dup2(log_fd, STDOUT_FILENO);//复制文件描述符dup2()相当于调用fcntl(oldfd, F_DUPFD, newfd);
        dup2(log_fd, STDERR_FILENO);
}
*/



//安装信号

signal(SIGUSR1,sig_stop); 



//socket


sock_fd=socket(AF_INET,SOCK_STREAM,0);

if(sockfd<0)//没连上服务器
{
   if(sock_fd=connect_server(*listen_ip,listen_port)<0)//在这个函数里调用socket，然后connect连接服务器，连接成功，返回fd
    {
       syslog("connect to server failure:%s",strerror(errno));

     }
    else if 
     {
       syslog("connect to server successful");
     }
}

if(sockfd>=0)//服务器连上了
{
    if(0==send_temprt_to_server())   
    {
          syslog("send ok");
         
    }
    else if
    { 
          syslog("send failure");
          sock_connected=NULL;
          close(sockfd);

    }
 //  sleep(30);

}

}

int connect_server(char *listen_ip, int listen_port)
{

 	int                      listen_fd, client_fd =-1;
        char                     buf[1024];
        struct sockaddr_in       serv_addr;
        int                      rv=-1;
        struct sockaddr_in       client_addr;
        socklen_t                clientaddr_len;
	int				on=1


        listen_fd=socket(AF_INET,SOCK_STREAM,0);

        if(listen_fd<0)
        {
                printf("create socket failure:%s\n",strerror(errno));
                return -1;
        }
        printf("create fd[%d]",listen_fd);
	setsockopt(listen_fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family=AF_INET;
        serv_addr.sin_port=htons(listen_port);


	 if( !listen_ip )
    {   
        serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    }   
    else
    {   
        if( inet_pton(AF_INET,listen_ip, &serv_addr.sin_addr) <= 0 )
        {   
            printf("Inet_pton() set listen IP address failure\n");
            rv = -2; 
            goto cleanup;
        }   
    }

        rv=bind(listen_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
        if(rv<0)
        {
                printf("bind failure:%s",strerror(errno));
                rv=-3;
		goto cleanup;
        }
        printf("socket[%d]bind on port [%d] for all ip address ok\n",listen_fd,listen_port);
        if(listen(listen_fd,BACKLOG)<0);
	{
		printf("use bind() to bind the TCP socket failure:%s\n",strerror(errno));
		rv=-4;
		goto cleanup;
	}
	cleanup:
		if(rv<0)
			close(listen_fd);
		else
			rv=listen_fd;

}
//epoll
if ((epollfd=epoll_create(MAX_EVENTS))<0)
{
	printf("epoll create failure:%s\n",strerror(errno));
	return 0;
}
while(!g_stop)
{
	events=epoll_wait(epollfd,event_array,MAX_EVENTS,-1);
	if(events<0)
	{
		printf("epoll failure:%s\n",strerror(errno));
		break;
	}
	else if(events==0)

	{
		printf("epoll get timeout\n");
		continue;
	}
	for(i=0;i<events,i++)
	{
		if((events_array[i].events&EPOLLERR)||(event_array[i].events &EPOLLHUP))
		{
			printf("epoll_wait get error on fd[%d]:%s\n",event_array[i].data.fd,strerror(errno));
			epoll_ctl(epollfd,EPOLL_CTL_DEL,event_array[i].data.fd,NULL);
			close(event_array[i].data.fd);
		}
		if(event_array[i].data.fd==listen_fd)
		client_fd=accept(listen_fd,(struct sockaddr*) & cli_addr, &len);
                if (client_fd < 0)
                {
                    printf("Accept the request from client failure:%s\n", strerror(errno));
                    continue;
                }
                event.data.fd = client_fd;
                event.events = EPOLLIN;
                if (epoll_ctl(epollfd, EPOLL_CTL_ADD, cli_fd, &event) < 0)
                {
                    printf("epoll add client socket failure:%s\n", strerror(errno));
                    close(client_fd);
                    continue;
                }
            }
            else
            {
                memset(buf, 0, sizeof(buf));

                a = read(cli_fd, buf, sizeof(buf));		
                if (a < 0)		
                {
                    printf("Read information from client failure:%s\n", strerror(errno));
                    close(client_fd);
                    exit(0);
                }
                else if (a == 0)		
                {
                    printf("The connection with client has broken!\n");
                    close(client_fd);
                    exit(0);
                }
                else		
                {
                    printf("%s\n",buf);
                   // sqlite_tem(buf);
                    printf("Database inserted successfully!\n");  
                }
                
            }
        }
    }
    close(listen_fd);

    return 0;
		
	




	

